import axios, { AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig, AxiosRequestHeaders } from 'axios';
import { showToast, showLoadingToast, closeToast } from 'vant';
import router from '../../router';

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000, // 请求超时时间
  withCredentials: true // 跨域请求时发送Cookie
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token');
    if (token) {
      // 让每个请求携带自定义token
      if (!config.headers) {
        config.headers = {} as AxiosRequestHeaders;
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => {
    // 对请求错误做些什么
    console.error('请求错误', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    
    // 如果响应的状态码不是200，说明请求有问题
    if (res.code !== 0 && res.code !== 200) {
      showToast({
        message: res.message || '请求失败',
        type: 'fail',
        duration: 3000,
      });
      
      // 处理特定的错误码
      if (res.code === 401) {
        // 未登录或token过期
        localStorage.removeItem('token');
        router.push('/login');
      }
      
      return Promise.reject(new Error(res.message || '请求失败'));
    }
    
    return res;
  },
  (error: AxiosError) => {
    console.error('响应错误', error);
    
    // 处理网络错误等异常情况
    const message = error.response?.data && typeof error.response.data === 'object' 
      ? (error.response.data as any).message 
      : error.message || '网络异常';
    
    showToast({
      message,
      type: 'fail',
      duration: 3000,
    });
    
    return Promise.reject(error);
  }
);

// 封装GET请求
export function get<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.get(url, { params, ...config });
}

// 封装POST请求
export function post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.post(url, data, config);
}

// 封装PUT请求
export function put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.put(url, data, config);
}

// 封装DELETE请求
export function del<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.delete(url, { params, ...config });
}

// 带加载提示的请求
export async function loadingRequest<T>(requestFn: Promise<T>, loadingText = '加载中...'): Promise<T> {
  showLoadingToast({
    message: loadingText,
    forbidClick: true,
    duration: 0,
  });
  try {
    const result = await requestFn;
    closeToast();
    return result;
  } catch (error) {
    closeToast();
    throw error;
  }
}

export default service; 